package org.springframework.samples.petclinic.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
import org.springframework.web.servlet.ajax.json.AjaxContext;

//TODO  This should probably be an injected colloborator rather than a
//superclass.
public class PetAndVisit {
	private final Clinic clinic;
	
	protected PetAndVisit(Clinic clinic){
		this.clinic = clinic;
	}
	
	public Clinic getClinic(){
		return this.clinic;
	}
	
	protected int findIndex(Pet pet){
		Owner owner = this.clinic.loadOwner(pet.getOwner().getId());
		List<Pet> pets = owner.getPets();
		int index = -1;
		for(int i = 0; i < pets.size(); i++){
			//Amazingly, petclinic's Pet does not have a valid equal method, so we check that ids are equal,
			//which will work fine.
			if(pet.getId().equals(pets.get(i).getId())){
				index = i;
				break;
			}
		}
		if(index == -1)
			throw new RuntimeException("Could not find pet " + 
					+ pet.getId() + " among owner " + owner.getId() +"'s pets.");
		return index;
	}	
	
	protected void preparePartial(int index, Pet pet, boolean highlight){
		Map modelOverride = new HashMap();
		modelOverride.put("index", index);
		modelOverride.put("pet", pet);
		AjaxContext.getJson().addPartial("petAndVisitDiv_" + index, "petAndVisit_", modelOverride);
		
		if(highlight){
			String js = "$('#petAndVisitDiv_" + index +"').fadeOut('slow'); + " +
				"$('#petAndVisitDiv_" + index +"').fadeIn('slow');";
			AjaxContext.getJson().addJavascript(js);
		}
	}
	
	protected void makePopup(String formName, String formId){
		AjaxContext.getJson().addPartial("popup", formName);
		//TODO When we start using live query plugin we won't need to add remoteForm here.
		AjaxContext.getJson().addJavascript("$.remoteForm('" + formId + "')");
	}		
	
}
